<template>
  <!-- <div style="position: relative;width:100%;height:100%"> -->
  <video
    class="video-player"
    ref="video"
    autoplay
    disablePictureInPicture
    poster="@/assets/images/loader-thumb.jpg"
  ></video>
  <!-- <TimeLine
      ref="Timeline"
      :startTime="videoConf.startTime"
      :endTime="videoConf.endTime"
      style="position: absolute; bottom: 14px; left: 0; right: 0; height: 60px"
      @timeChange="timeChange"
    ></TimeLine> -->
  <!-- </div> -->
</template>
<script>
  import { unref } from 'vue';
  import dayjs from 'dayjs';

  export default {
    name: 'NstdVideoPlayerWfs',
    props: {
      // 播放类型 1实时视频，2视频回放
      playType: {
        type: String,
        default: 'realVideo'
      },
      sendType: {
        type: String,
        default: ''
      },
      index: {
        type: Number,
        default: 0
      },
      videoConf: {
        type: Object,
        default: () => {}
      },
      reconnect: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        times: 0,
        websocket: null,
        flag: false,
        player: null,
        heartBeatTime: null,
        openMsgConf: {}, // 建立长链接请求配置
        closeMsgConf: {}, // 关闭长链接请求配置
        sendMsgConf: {}, // 发送长链接请求配置
        heartBeatConf: {} // 心跳连接配置
      };
    },
    watch: {
      sendType: {
        handler(n) {
          if (n) {
            if (n === 'backVideoScale') return false;
            const { key, nvrCode, v } = this.videoConf;
            const sendMsgObj = {
              backVideoPause: {
                t: 'backVideoPause',
                c: nvrCode,
                v: key
              },
              backVideoRetPlay: {
                t: 'backVideoRetPlay',
                c: nvrCode,
                v: key
              }
              // backVideoScale: {
              //   t: "backVideoScale",
              //   c: nvrCode,
              //   v: key + "|" + v,
              // },
            };
            this.sendMsgConf = sendMsgObj[n];
            this.onsend();
          }
        },
        immediate: true
      },
      videoConf: {
        handler(n) {
          const { key } = this.videoConf;
          if (this.sendType === 'backVideoScale') {
            this.sendMsgConf = {
              t: 'backVideoScale',
              c: n.nvrCode,
              v: key + '|' + n.v
            };
            this.wfs.bufferController.checkPendingTracks();
            this.$refs.video.playbackRate = n.v.toFixed(1);
            this.onsend();
            return;
          }
          if (this.sendType) {
            return;
          }
          if (!n) {
            if (!this.wfs) {
              return;
            }
            this.closeWebsocket();
          } else {
            this.$nextTick(() => {
              this.closeWebsocket();
              this.setInitConf();
              this.initJMuxer();
              this.inintSocket();
            });
          }
        },
        deep: true,
        immediate: true
      }
    },
    mounted() {
      // this.$refs.Timeline.createTimeSlider(Date.now());
    },
    destroyd() {
      this.wfs && this.wfs.destroy();
    },
    methods: {
      timeChange(e) {
        // this.$refs.video.pause();
        console.log('timeChange');
        this.seekend(e);
      },
      seekend(currentTime) {
        if (this.playType === 'realVideo') return false;
        const { key, nvrCode, startTime } = this.videoConf;
        const sendMsgConf = {
          t: 'backVideoByPos',
          c: nvrCode,
          k: '',
          v: key + '|' + dayjs(currentTime).format('YYYY-MM-DD HH:mm:ss')
        };
        this.wfs.websocketLoader.onWebsocketDataUploading({
          data: JSON.stringify(sendMsgConf)
        });
        // const sourceBuffer = this.wfs.bufferController.sourceBuffer.video
        // sourceBuffer.remove(sourceBuffer.buffered.start(0),sourceBuffer.buffered.end(0))
        // this.wfs.bufferController.onBufferReset({
        //    mimeType : "video/mp4;codecs=avc1.4d002a"
        // })
        // const  currentTimes = this.wfs.media.currentTime
        // if(sourceBuffer.buffered.length > 0){
        //   let end = sourceBuffer.buffered.end(0)
        //   if(end - currentTimes > 0.15){
        //     this.wfs.media.currentTime = end - 0.1
        //   }
        // }
        this.wfs.bufferController.reset();
        this.wfs.media.play();
      },
      ended(e) {
        console.log(e, 'e');
      },
      setInitConf() {
        const { videoConf, playType } = this;
        const { nvrChannel, key, nvrCode } = videoConf;
        const openMsgObj = {
          realVideo: {
            t: 'realVideoOpen',
            c: nvrCode,
            v: String(nvrChannel)
          },
          backVideo: {
            t: 'backVideoOpen',
            c: nvrCode,
            v: key
          }
        };
        const closeMsgObj = {
          realVideo: {
            t: 'realVideoClose',
            c: nvrCode,
            v: String(nvrChannel)
          },
          backVideo: {
            t: 'backVideoClose',
            c: nvrCode,
            v: key
          }
        };
        const heartBeatObj = {
          realVideo: {
            t: 'heartBeat',
            c: nvrCode,
            v: String(nvrChannel)
          },
          backVideo: {
            t: 'heartBeat',
            c: nvrCode,
            v: key
          }
        };
        this.openMsgConf = openMsgObj[playType];
        this.closeMsgConf = closeMsgObj[playType];
        this.heartBeatConf = heartBeatObj[playType];
      },
      // 初始化JMuxer
      initJMuxer() {
        this.wfs = new Wfs();
        window.wfs = this.wfs;
      },
      // 初始化长链接
      inintSocket(reconnect) {
        console.log(reconnect, 'reconnect');
        const video = this.$refs.video;
        const { c, t, v } = this.openMsgConf;
        // const duration = new Date(endTime).valueOf() - new Date(startTime).valueOf()
        const { protocol, host } = location;
        let wsProtocol = protocol === 'http:' ? 'ws://' : 'wss://';
        const socketURL = `${wsProtocol}${host}/voiceStreamWs/`;
        this.wfs.attachMedia(this.$refs.video, c, 'H264Raw', socketURL, t, v, null, (socket) => {
          this.$message.success('视频回放完成');
          clearInterval(this.heartBeatTime);
          console.log(this.wfs);
          video.src = '';
          this.$emit('complete');
        });
        this.heartBeat();
      },
      closeWebsocket() {
        const { c, v, t } = this.closeMsgConf;
        console.log('JSON.stringify(this.closeMsgConf)', JSON.stringify(this.closeMsgConf));
        if (this.wfs) {
          this.wfs.closeWebSocket(c, t, v);
          this.wfs.websocketLoader.onWebsocketDataUploading({
            data: JSON.stringify(this.closeMsgConf)
          });
          this.wfs.websocketLoader.destroy();
        }
      },
      onsend() {
        this.wfs.websocketLoader.onWebsocketDataUploading({
          data: JSON.stringify(this.sendMsgConf)
        });
      },
      heartBeat() {
        // if (!this.wfs.websocketLoader.client) {
        //   return false;
        // }
        this.heartBeatTime = setInterval(() => {
          if (!this.wfs.websocketLoader.client) return false;
          if (this.wfs.websocketLoader.client.readyState === 3) {
            clearInterval(this.heartBeatTime);
            console.log('111111');
            if (this.reconnect && this.times < 3) {
              console.log('22222');
              this.times++;
              // 重连socket
              this.inintSocket(true);
            }
          } else if (this.wfs.websocketLoader.client.readyState === 1) {
            console.log('3333');
            this.wfs.websocketLoader.onWebsocketDataUploading({
              data: JSON.stringify(this.heartBeatConf)
            });
            if (this.playType === 'backVideo') {
              // 获取回放视频播放进度
              this.wfs.websocketLoader.onWebsocketDataUploading({
                data: JSON.stringify({
                  t: 'backVideoGetPos',
                  c: this.videoConf.nvrCode,
                  v: this.videoConf.key
                })
              });
            }
          }
        }, 5000);
      }
    }
  };
</script>
<style lang="less" scoped>
  .video-player {
    width: 100%;
    height: 100%;
    background: #000;

    ::v-deep .video-js {
      width: 100%;
      height: 100%;
    }
  }
</style>
